package com.gy.api.mobile.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import com.gy.api.base.Constants;
import com.gy.api.base.RedisUtils;
import com.gy.api.base.RsaKeyProperties;
import com.gy.api.base.Type;
import com.gy.api.mobile.company.dao.CompanyInfoDao;
import com.gy.api.mobile.company.domain.po.CompanyInfoPO;
import com.gy.api.mobile.company.domain.vo.CompanyInfoVO;
import com.gy.api.mobile.company.domain.vo.CompanyLoginResVO;
import com.gy.api.mobile.user.dao.MobileUserDao;
import com.gy.api.mobile.user.domain.po.MobileUserPO;
import com.gy.api.mobile.user.domain.vo.*;
import com.gy.api.mobile.user.domain.vo.UserLoginResVO;
import com.gy.api.mobile.user.service.IUserService;
import com.gy.api.pc.sys.user.dao.SysUserDao;
import com.gy.api.pc.sys.user.domain.po.SysUserPO;
import com.gy.api.pc.user.domain.vo.MobileUserSearchVO;
import com.gy.api.pc.user.domain.vo.MobileUserVO;
import com.gy.api.sms.service.DynamicMessageService;
import com.gy.exception.BusinessException;
import com.gy.util.EncryptionUtils;
import com.gy.util.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.security.PrivateKey;
import java.util.List;


@Service
@Transactional
@Slf4j
public class UserServiceImpl implements IUserService {
    @Autowired
    private MobileUserDao mobileUserDao;
    @Autowired
    private RsaKeyProperties rsaKeyProperties;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private DynamicMessageService smsService;

    @Override
    public UserLoginResVO login_password(UserLoginVO userLoginVO) {
        try{
            PrivateKey privateKey = rsaKeyProperties.getPrivateKey();
            userLoginVO.setPassword(RsaUtils.decrypt(userLoginVO.getPassword(), privateKey));
        }catch (Exception e){
//            e.printStackTrace();
            throw new BusinessException(Type.FAIL.getCode(),"密码错误");
        }
        Example sysExample = new Example(MobileUserPO.class);
        sysExample.and().andEqualTo("userPhone",userLoginVO.getPhone())
                .andEqualTo("delFlag", Constants.DEL_FLAG_FALSE);
        MobileUserPO loginUser=mobileUserDao.selectOneByExample(sysExample);
        if(!EncryptionUtils.match(loginUser.getId()+userLoginVO.getPassword(),loginUser.getLoginPassword())){
            throw new BusinessException(Type.FAIL.getCode(),"账号密码错误！");
        }
        StpUtil.login(loginUser.getId(),"h5_user");
        UserLoginResVO resVO =new UserLoginResVO();
        resVO.setToken(StpUtil.getTokenValue());
        return resVO;
    }

    @Override
    public UserLoginResVO login_code(UserLoginCodeVO userLoginVO) throws Exception {
        Example sysExample = new Example(MobileUserPO.class);
        sysExample.and().andEqualTo("userPhone",userLoginVO.getPhone())
                .andEqualTo("delFlag", Constants.DEL_FLAG_FALSE);
        MobileUserPO loginUser=mobileUserDao.selectOneByExample(sysExample);

        String code= redisUtils.get(Constants.CAPTCHA_CODE_KEY +"_"+userLoginVO.getPhone()+"_"+1);
        if(StringUtils.isEmpty(userLoginVO.getCode())){
            throw new BusinessException(Type.FAIL.getCode(),"登陆验证码不能为空");
        }
        if(!userLoginVO.getCode().equals(code)){
            throw new BusinessException(Type.FAIL.getCode(),"登陆验证码不正确");
        }
        redisUtils.delete(Constants.CAPTCHA_CODE_KEY +"_"+userLoginVO.getPhone()+"_"+1);
        if(loginUser==null){
            //创建用户
            loginUser=new MobileUserPO();
            loginUser.setUserName("用户"+ RandomUtil.randomString(16));
            loginUser.setUserSex(1);
            loginUser.setUseState(1);
            loginUser.setUserPhone(userLoginVO.getPhone());
            loginUser.setLoginName(userLoginVO.getPhone());
            String password= RandomUtil.randomString (6);
            smsService.sendDynamicMessage("【光影重庆】您好，用户信息注册成功，您的初始登录密码为:"+password+"，请不要泄漏给其他人。",loginUser.getUserPhone());
            loginUser.preInsert();
            loginUser.setLoginPassword(EncryptionUtils.encrypt(loginUser.getId()+password));
            mobileUserDao.insertSelective(loginUser);
        }
        StpUtil.login(loginUser.getId(),"h5_user");
        UserLoginResVO resVO =new UserLoginResVO();
        resVO.setToken(StpUtil.getTokenValue());
        return resVO;
    }

    @Override
    public MobileUserPO selectUserByPhone(String phone) {
        Example sysExample = new Example(MobileUserPO.class);
        sysExample.and().andEqualTo("userPhone",phone)
                .andEqualTo("delFlag", Constants.DEL_FLAG_FALSE);
        return mobileUserDao.selectOneByExample(sysExample);
    }
    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public UserVO getOne() {
        MobileUserPO mobileUserPO=mobileUserDao.selectByPrimaryKey(StpUtil.getLoginId());
        SysUserPO loginUser=sysUserDao.selectByPrimaryKey(StpUtil.getLoginId());
        if(mobileUserPO==null&&loginUser==null){
            throw new BusinessException(Type.FAIL.getCode(),"用户信息未找到");
        }
        UserVO vo=new UserVO();
        if(mobileUserPO!=null){
            BeanUtils.copyProperties(mobileUserPO, vo);
            vo.setUserType(1);
        }
        if(loginUser!=null){
            vo.setId(loginUser.getId());
            vo.setUserName(loginUser.getUserName());
            vo.setUserPhone(loginUser.getUserPhone());
            vo.setUserType(2);
        }
        return vo;
    }

    @Override
    public void updateName(UpdateUserNameVO userNameVO) {
        MobileUserPO mobileUserPO=mobileUserDao.selectByPrimaryKey(StpUtil.getLoginId());
        if(mobileUserPO==null){
            throw new BusinessException(Type.FAIL.getCode(),"用户信息未找到");
        }
        mobileUserPO.setUserName(userNameVO.getUserName());
        mobileUserPO.preUpdate();
        mobileUserDao.updateByPrimaryKeySelective(mobileUserPO);
    }

    @Override
    public void bindingPhone(UserCodeVO userCodeVO) {
        MobileUserPO mobileUserPO=mobileUserDao.selectByPrimaryKey(StpUtil.getLoginId());
        String code= redisUtils.get(Constants.CAPTCHA_CODE_KEY +"_"+userCodeVO.getPhone()+"_"+4);
        if(StringUtils.isEmpty(userCodeVO.getCode())){
            throw new BusinessException(Type.FAIL.getCode(),"验证码不能为空");
        }
        if(!userCodeVO.getCode().equals(code)){
            throw new BusinessException(Type.FAIL.getCode(),"验证码不正确");
        }
        mobileUserPO.setUserPhone(userCodeVO.getPhone());
        mobileUserPO.setLoginName(userCodeVO.getPhone());
        mobileUserPO.preUpdate();
        mobileUserDao.updateByPrimaryKeySelective(mobileUserPO);
    }

    @Override
    public void updateUserPasswordPhone(UpdateUserPasswordPhoneVO phoneVO) {
        Example sysExample = new Example(MobileUserPO.class);
        sysExample.and().andEqualTo("userPhone",phoneVO.getPhone())
                .andEqualTo("delFlag", Constants.DEL_FLAG_FALSE);
        MobileUserPO sysUser=mobileUserDao.selectOneByExample(sysExample);
        if(sysUser==null){
            throw new BusinessException(Type.FAIL.getCode(),"该手机号码还未注册");
        }
        try{
            PrivateKey privateKey = rsaKeyProperties.getPrivateKey();
            phoneVO.setNewPassword(RsaUtils.decrypt(phoneVO.getNewPassword(), privateKey));
        }catch (Exception e){
//            e.printStackTrace();
            throw new BusinessException(Type.FAIL.getCode(),"密码错误");
        }
        sysUser.setLoginPassword(EncryptionUtils.encrypt(sysUser.getId()+phoneVO.getNewPassword()));
        sysUser.preUpdate();
        mobileUserDao.updateByPrimaryKeySelective(sysUser);
    }

    @Override
    public void updateUserPasswordVO(UpdateUserPasswordVO updateUserPasswordVO) {
        try{
            PrivateKey privateKey = rsaKeyProperties.getPrivateKey();
            updateUserPasswordVO.setNewPassword(RsaUtils.decrypt(updateUserPasswordVO.getNewPassword(), privateKey));
            updateUserPasswordVO.setOldPassword(RsaUtils.decrypt(updateUserPasswordVO.getOldPassword(), privateKey));
        }catch (Exception e){
//            e.printStackTrace();
            throw new BusinessException(Type.FAIL.getCode(),"密码错误");
        }
        MobileUserPO sysUser=mobileUserDao.selectByPrimaryKey(StpUtil.getLoginId());
        if(sysUser==null){
             new BusinessException(Type.FAIL.getCode(),"未找到用户信息!");
        }
        if(!EncryptionUtils.match(sysUser.getId()+updateUserPasswordVO.getOldPassword(),sysUser.getLoginPassword())){
            throw new BusinessException(Type.FAIL.getCode(),"账号密码错误！");
        }
        sysUser.setLoginPassword(EncryptionUtils.encrypt(sysUser.getId()+updateUserPasswordVO.getNewPassword()));
        sysUser.preUpdate();
        mobileUserDao.updateByPrimaryKeySelective(sysUser);
    }

    @Override
    public List<MobileUserVO> getList(MobileUserSearchVO searchVO) {
        return mobileUserDao.getList(searchVO);
    }
}